package com.hww.acommon;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.hww.acommon.databinding.ActivityMainBinding;
import com.hww.acommon.test.BitmapGrayUtilsActivity;
import com.hww.acommon.test.DialogActivity;
import com.hww.acommon.test.ImageActivity;
import com.hww.acommon.test.PermissionActivity;
import com.hww.acommon.test.ToastActivity;
import com.hww.acommon.test.UtilsIntentActivity;
import com.hww.acommon.test.ViewActivity;
import com.hww.common.MyAppThis;
import com.hww.common.util.CrashUtils;
import com.hww.common.util.LogUtils;
import com.hww.common.util.MD5Utils;
import com.hww.common.util.NetworkUtils;
import com.hww.common.util.ResourceUtils;
import com.hww.common.util.SDCardUtils;
import com.hww.common.util.ThreadUtils;
import com.hww.common.util.ToastUtils;
import com.hww.dialog.SweetAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.ExecutorService;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    private static final ExecutorService cpuPool = ThreadUtils.getCpuPool();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        CrashUtils.init("/sdcard/crash/");

        /*setContentView(R.layout.activity_main);*/
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        for (String s : LIST) {
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            Button button = new Button(this);
            button.setLayoutParams(layoutParams);
            button.setText(s);
            button.setGravity(Gravity.CENTER);
            button.setOnClickListener(clickListener);
            binding.mainLinearLayout.addView(button);
        }

        textSDCard();
    }

    private boolean isStatus = true;

    private static final String[] LIST = new String[]{"intent",
            "bitmapGray", "permission", "image",
            "network", "MD5", "Log", "dialog", "Toast","view"};
    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v instanceof Button) {
                Intent intent = null;
                Button b = (Button) v;
                CharSequence text = b.getText().toString().trim();
                if (LIST[1].equals(text)) {
//                    testResUtils();
//                    if (isStatus) {
//                        KeyboardUtils.showSoftInput(MainActivity.this);
//                    } else {
//                        KeyboardUtils.hideSoftInput(MainActivity.this);
//                    }
//                    isStatus = !isStatus;

                    intent = new Intent(MainActivity.this, BitmapGrayUtilsActivity.class);

                } else if (LIST[0].equals(text)) {
                    intent = new Intent(MainActivity.this, UtilsIntentActivity.class);
                } else if (LIST[2].equals(text)) {
                    intent = new Intent(MainActivity.this, PermissionActivity.class);
                } else if (LIST[3].equals(text)) {
                    intent = new Intent(MainActivity.this, ImageActivity.class);
                } else if (LIST[4].equals(text)) {
                    /*NetworkUtils.openWirelessSettings();*/
                    cpuPool.execute(() -> {
                        testNetworkUtils();
                    });
                } else if (LIST[5].equals(text)) {
                    cpuPool.execute(() -> {
                    });
                    testMD5Utils();
                } else if (LIST[6].equals(text)) {
                    testLogUtils();
                } else if (LIST[7].equals(text)) {
                    intent = new Intent(MainActivity.this, DialogActivity.class);
                } else if (LIST[8].equals(text)) {
                    intent = new Intent(MainActivity.this, ToastActivity.class);
                } else if (LIST[9].equals(text)) {
                    intent = new Intent(MainActivity.this, ViewActivity.class);
                } else {
                }
                if (null != intent) {
                    startActivity(intent);
                }
            }
        }
    };

    private void textSDCard() {
        cpuPool.execute(() -> {
            System.out.println("--------------sdcard");

            String filesDir = SDCardUtils.getFilesDir();
            String cacheDir = SDCardUtils.getCacheDir();
            String externalFilesDir = SDCardUtils.getExternalFilesDir();
            String externalCacheDir = SDCardUtils.getExternalCacheDir();
            String externalStorageDirectory = SDCardUtils.getExternalStorageDirectory();
            String externalFilesDir1 = SDCardUtils.getExternalFilesDir(null);

            LogUtils.i(filesDir, cacheDir, externalFilesDir, externalCacheDir, externalStorageDirectory, externalFilesDir1);

            System.out.println("--------------sdcard");
        });
    }

    private void testResUtils() {
        cpuPool.execute(() -> {
            System.out.println("--------------*****");
            String path = "zyConfig.txt";
            boolean b = ResourceUtils.copyFileFromAssets(path, "/img/zyConfig.txt");

            System.out.println("--------------copy = " + b);

            String s = ResourceUtils.readAssets2String(path);
            System.out.println("--------------readAssets2String = " + s);
        });
    }

    private void testLogUtils() {
        LogUtils.getConfig().setFilePrefix("custom_");
        LogUtils.iTag("tag001", "testLogUtils001", "testLogUtils002");
        LogUtils.i("testLogUtils00100", "testLogUtils00200");

        LogUtils.file("测试保存日志内容001");
        LogUtils.file("tag_file001", "测试保存日志内容001");
        LogUtils.file("tag_file002", "测试保存日志内容00100");

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("a", "ab");
            jsonObject.put("a2", "abcd");
            jsonObject.put("a3", "abcdef");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        LogUtils.json(jsonObject);

        try {
            /*去除异常捕获，可用于测试CrashUtil的功能*/
            String a = null;
            a.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        ToastUtils.success(MyAppThis.getThis(), "保存日志成功").show();
    }

    private void testMD5Utils() {
        try {
            String path = "/sdcard/DCIM/";
            String md5String = MD5Utils.getMD5String(path.getBytes());
            ToastUtils.success(MyAppThis.getThis(), path + "\n" + "MD5: " + md5String).show();

            System.out.println("MD5Utils===> " + md5String);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void testNetworkUtils() {
        try {
            showAlertDialog(true);
            try {
                String host = "192.168.10.85";
                int port = 10010;
                boolean b = NetworkUtils.testSocket(host, port);
                String format1 = String.format("networkUtils===> %s:%s socket连接:%s ", host, port, b);
                System.out.println(format1);
                port = 10011;
                boolean b1 = NetworkUtils.testSocket(host, port);
                System.out.printf("networkUtils===> %s:%s socket连接:%s ", host, port, b);
            } catch (Exception e) {
                e.printStackTrace();
            }

            NetworkUtils.registerNetworkStatusChangedListener(onNetworkStatusChangedListener);

            try {
                NetworkUtils.addOnWifiChangedConsumer(scanConsumer);
            } catch (Exception e) {
                e.printStackTrace();
            }

            StringBuilder builder = new StringBuilder();
            String domain = "www.baidu.com";
            String domainAddress = NetworkUtils.getDomainAddress(domain);
            builder.append("networkUtils===> " + domain + " 解析的IP地址: " + domainAddress).append("\n");

            String ipV4Address = NetworkUtils.getIPAddress(true);
            String ipV6Address = NetworkUtils.getIPAddress(false);
            builder.append("networkUtils===> " + "ipV4Address: " + ipV4Address).append("\n");
            builder.append("networkUtils===> " + "ipV6Address: " + ipV6Address).append("\n");

            NetworkUtils.NetworkType networkType = NetworkUtils.getNetworkType();
            builder.append("networkUtils===> " + "networkType: " + networkType).append("\n");

            String networkOperatorName = NetworkUtils.getNetworkOperatorName();
            builder.append("networkUtils===> " + "网络运营商名称: " + networkOperatorName).append("\n");

            boolean wifiConnected = NetworkUtils.isWifiConnected();
            builder.append("networkUtils===> " + "wifi是否连接: " + wifiConnected).append("\n");


            boolean availableByPing = NetworkUtils.isAvailableByPing(domain);
            builder.append("networkUtils===> " + "ping: " + availableByPing).append("\n");
            NetworkUtils.isAvailableByPing("192.168.9.165", new NetworkUtils.Consumer<String>() {
                @Override
                public void accept(String s) {
                    Log.e("ping", s);
                }
            });

            boolean connected = NetworkUtils.isConnected();
            builder.append("networkUtils===> " + "connected: " + connected).append("\n");

            boolean mobileDataEnabled = NetworkUtils.getMobileDataEnabled();
            builder.append("networkUtils===> " + "mobileDataEnabled: " + mobileDataEnabled).append("\n");
            try {
                NetworkUtils.setWifiEnabled(true);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String s = builder.toString();
            System.out.println("networkUtils===> \n" + s);

            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.success(MainActivity.this, s).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            showAlertDialog(false);
        }
    }

    NetworkUtils.OnNetworkStatusChangedListener onNetworkStatusChangedListener = new NetworkUtils.OnNetworkStatusChangedListener() {
        @Override
        public void onDisconnected() {
            System.out.println("networkUtils===> " + "网络断开");
        }

        @Override
        public void onConnected(NetworkUtils.NetworkType networkType) {
            System.out.println("networkUtils===> " + "网络连接成功  " + networkType.name());
        }
    };

    NetworkUtils.Consumer scanConsumer = new NetworkUtils.Consumer<NetworkUtils.WifiScanResults>() {
        @Override
        public void accept(NetworkUtils.WifiScanResults wifiScanResults) {
            System.out.println("networkUtils===> " + "wifiScanResults: " + wifiScanResults);
        }
    };


    private SweetAlertDialog sweetAlertDialog = null;

    private void showAlertDialog(boolean status) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status) {
                    sweetAlertDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.PROGRESS_TYPE);
                    sweetAlertDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                    sweetAlertDialog.setTitleText("网络测试中...");
                    sweetAlertDialog.setCancelable(true);
                    sweetAlertDialog.setCanceledOnTouchOutside(true);
                    sweetAlertDialog.show();
                } else {
                    if (null != sweetAlertDialog) {
                        sweetAlertDialog.cancel();
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        NetworkUtils.unregisterNetworkStatusChangedListener(onNetworkStatusChangedListener);
        NetworkUtils.removeOnWifiChangedConsumer(scanConsumer);
    }
}
